import { fileURLToPath, URL } from "node:url";

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  base: "./",
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
  server:{
    port: 5175,
    proxy: {
        "/apiA":{
            //代理url前面的部分
            target:"http://localhost:8081/tiny_wind_diary_server_war_exploded",
            ws:true,
            changeOrigin:true,
            rewrite: (path) => {
                console.log(`path is: ${path}`);
                let np = path.replace(/^\/apiA/, "");
                console.log(`proxy path is: ${np}`);
                return np;
            },
            configure:(proxy, options)=> {
                proxy.on("error",function(req,res,target) {
                    console.log("on error");
                }),
                //start并不是服务器启动,而是一次请求的开始.
                proxy.on('start',function(req,res,target){
                    console.log(`\n+++ proxy start +++`)
                    console.log(`target is ${JSON.stringify(target)}`)
                    console.log(`req is ${JSON.stringify(req.headers)}`)
                    console.log(`res is ${JSON.stringify(res.statusCode)}`)
                    console.log(`=== proxy end ===\n`)

                }),
                //获得响应后
                proxy.on('proxyRes', function (proxyRes:IncomingMessage, req:IncomingMessage, res) {
                    console.log(`\n+++proxyRes start+++`)
                    let setCookieValue = proxyRes.headers['set-cookie'];
                    if (setCookieValue) {
                        // 域名信息与实际业务相关
                        let cookieString = setCookieValue[0];
                        let cookieK = cookieString.split(`;`)[0];
                        // cookie = cookieK
                        // console.log(`cookie is ${cookie}`);
                    }
                    console.log(`proxy==>target: ${proxyRes.url}`);
                    // console.log('RAW Response from the target', JSON.stringify(proxyRes.headers));
                    // new URL(request.url, `http://${request.getHeaders().host}`)
                    console.log(`${JSON.stringify(proxyRes.url)}`);
                    console.log(`req.url: ${JSON.stringify(req.url)},${req.headers.host}`)
                    console.log(`${JSON.stringify(res.statusMessage)}`);
                    console.log(`===proxyRes start===\n`)
                });
                //发送请求前
                proxy.on('proxyReq', function (proxyReq:ClientRequest, req:IncomingMessage, res:ServerResponse<IncomingMessage>) {
                    console.log(`\n+++proxyReq start+++`)
                    // console.log(`req.url: ${JSON.stringify(proxyReq)}`)
                    console.log(`res code: ${JSON.stringify(res.statusCode)}`)
                    // const cookie = req.headers['cookie']
                    // if (cookie) {
                    //     proxyReq.setHeader('cookie', cookie)
                    // }
                    // proxyReq.setHeader('cookie',cookie);
                    // req.headers
                    // console.log(`RAW Request from the target`, JSON.stringify(proxyReq.getHeader));
                    console.log(`Proxy request to the target,${proxyReq.protocol}//${proxyReq.host}:${proxyReq.port}${proxyReq.path}`);
                    console.log(`===proxyReq start===\n`)
                    
                });
            },
        },
        "/apiB/oauth/2.0/token":{
            target:"https://api.caiyunapp.com/v2.6/2mJhlYpgMvpHrL1o/101.6656,39.2072/daily?dailysteps=1",
            ws:false,
            changeOrigin:true,
            rewrite: (path) => {
                console.log(`path is: ${path}`);
                let np = path.replace("/apiB/oauth/2.0/token", "");
                console.log(`proxy path is: ${np}`);
                return np;
            },
            configure:(proxy, options)=> {
                proxy.on("error",function(req,res,target) {
                    console.log("on error");
                }),
                //start并不是服务器启动,而是一次请求的开始.
                proxy.on('start',function(req:IncomingMessage,res,target:HttpProxy.ProxyTargetUrl){
                    console.log(`\n+++ proxy start +++`)
                    console.log(`target is ${JSON.stringify(target)}`)
                    console.log(`req is ${JSON.stringify(req.url?.toString())}`)
                    console.log(`res is ${JSON.stringify(res.statusCode)}`)
                    console.log(`=== proxy end ===\n`)

                }),
                proxy.on("end",(req: IncomingMessage, res: ServerResponse<IncomingMessage>, proxyRes: IncomingMessage)=>{
                    console.log(`\n+++end+++`)   
                    console.log(proxyRes.map(data=>{
                        console.log(data);
                    }))
                    console.log(`===end===\n`)   
                });
                //获得响应后
                proxy.on('proxyRes', function (proxyRes:IncomingMessage, req:IncomingMessage, res:ServerResponse<IncomingMessage>) {
                    console.log(`\n+++proxyRes start+++`)
                    let setCookieValue = proxyRes.headers['set-cookie'];
                    if (setCookieValue) {
                        // 域名信息与实际业务相关
                        let cookieString = setCookieValue[0];
                        let cookieK = cookieString.split(`;`)[0];
                        // cookie = cookieK
                        // console.log(`cookie is ${cookie}`);
                    }
                    console.log(`proxy==>target: ${proxyRes.url}`);
                    // console.log('RAW Response from the target', JSON.stringify(proxyRes.headers));
                    // new URL(request.url, `http://${request.getHeaders().host}`)
                    console.log(`${JSON.stringify(proxyRes.url)}`);
                    console.log(`req.url: ${JSON.stringify(req.url)},${req.headers.host}`)
                    console.log(`${JSON.stringify(res.statusMessage)}`);
                    console.log(`===proxyRes start===\n`)
                });
                //发送请求前
                proxy.on('proxyReq', function (proxyReq:ClientRequest, req:IncomingMessage, res:ServerResponse<IncomingMessage>) {
                    console.log(`\n+++proxyReq start+++`)
                    // console.log(`req.url: ${JSON.stringify(proxyReq)}`)
                    console.log(`proxyReq code: ${JSON.stringify(res.statusCode)}`)
                    console.log(`proxyReq method: ${JSON.stringify(proxyReq.method)}`)
                    console.log(`proxyReq host: ${JSON.stringify(proxyReq.host)}`)
                    res.addListener("error",()=>{
                        console.log("err");
                    })
                    res.addListener("close",()=>{
                        console.log("close");
                        console.log(`res statusMessage: ${res.statusMessage} ${res.statusCode}}`)
                        console.log(`${res.getHeaderNames()}`)
                    })
                    console.log(`res: ${res.statusMessage}`)
                    // const cookie = req.headers['cookie']
                    // if (cookie) {
                    //     proxyReq.setHeader('cookie', cookie)
                    // }
                    // proxyReq.setHeader('cookie',cookie);
                    // req.headers
                    // console.log(`RAW Request from the target`, JSON.stringify(proxyReq.getHeader));
                    console.log(`Proxy request to the target,${proxyReq.protocol}//${proxyReq.host}/${proxyReq.path}`);
                    console.log(`===proxyReq start===\n`)
                    
                });
            },
        }
    }
  }
});
